import { login, logout } from '@/api/user'
import { getUser, getRole, getStore,setUser,setRole,setStore,removeInfo } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  getUser: getUser(),
  getRole: getRole(),
  getStore: getStore(),

}

const mutations = {
  SET_USER: (state, user) => {
    state.getUser = user
    setUser(user)
  },
  SET_ROLE: (state, role) => {
    state.getRole = role
    setRole(role)
  },
  SET_STORE: (state, stores) => {
    state.getStore = stores
    setStore(stores)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), userPassword: password }).then(res => {
        resolve(res)
        if(res.code==200){
          const { data } = res
          commit('SET_USER', JSON.stringify(data.sysUser))
          commit('SET_ROLE', JSON.stringify(data.sysRole))
          commit('SET_STORE', JSON.stringify(data.store))
        }else{
          
        }
      
       
      }).catch(error => {
        reject("登录失败")
      })
    })
  },

  // get user info

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject("error")
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

